<template>
  <div class="login">
    <!-- 背景装饰 -->
    <div class="login-bg">
      <div class="login-bg-item"></div>
      <div class="login-bg-item"></div>
      <div class="login-bg-item"></div>
    </div>

    <!-- 登录表单 -->
    <div class="login-form">
      <div class="login-form-wrapper">
        <!-- Logo和标题 -->
        <div class="login-header">
          <img class="login-logo" src="@/assets/images/logo.png" alt="Kexilo" />
          <h2 class="login-title">Kexilo 权限管理系统</h2>
          <p class="login-subtitle">基于Spring Boot 3 + Vue 3的权限管理系统</p>
        </div>

        <!-- 登录表单 -->
        <el-form
          ref="loginFormRef"
          :model="loginForm"
          :rules="loginRules"
          class="login-form-content"
          @keyup.enter="handleLogin"
        >
          <!-- 用户名 -->
          <el-form-item prop="username">
            <el-input
              v-model="loginForm.username"
              type="text"
              size="large"
              placeholder="请输入用户名"
              prefix-icon="User"
              :maxlength="30"
              tabindex="1"
              auto-complete="on"
            />
          </el-form-item>

          <!-- 密码 -->
          <el-form-item prop="password">
            <el-input
              v-model="loginForm.password"
              type="password"
              size="large"
              placeholder="请输入密码"
              prefix-icon="Lock"
              :maxlength="20"
              tabindex="2"
              auto-complete="on"
              show-password
            />
          </el-form-item>

          <!-- 验证码 -->
          <el-form-item prop="code" v-if="captchaEnabled">
            <div class="captcha-container">
              <el-input
                v-model="loginForm.code"
                size="large"
                placeholder="请输入验证码"
                prefix-icon="Key"
                :maxlength="5"
                tabindex="3"
                auto-complete="off"
                class="captcha-input"
              />
              <div class="captcha-img" @click="getCaptcha">
                <img v-if="captchaImg" :src="captchaImg" alt="验证码" />
                <span v-else class="captcha-loading">加载中...</span>
              </div>
            </div>
          </el-form-item>

          <!-- 记住密码 -->
          <el-form-item>
            <div class="login-options">
              <el-checkbox v-model="rememberMe" tabindex="4">
                记住用户名
              </el-checkbox>
              <el-link type="primary" :underline="false" class="forgot-password">
                忘记密码？
              </el-link>
            </div>
          </el-form-item>

          <!-- 登录按钮 -->
          <el-form-item>
            <el-button
              :loading="loading"
              size="large"
              type="primary"
              style="width: 100%"
              @click="handleLogin"
              tabindex="5"
            >
              <span v-if="!loading">登 录</span>
              <span v-else>登录中...</span>
            </el-button>
          </el-form-item>
        </el-form>

        <!-- 页脚信息 -->
        <div class="login-footer">
          <p class="copyright">© 2024 Kexilo. All rights reserved.</p>
          <div class="links">
            <el-link type="info" :underline="false">隐私政策</el-link>
            <el-divider direction="vertical" />
            <el-link type="info" :underline="false">服务条款</el-link>
            <el-divider direction="vertical" />
            <el-link type="info" :underline="false">帮助中心</el-link>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, nextTick } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage, ElLoading } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import { useUserStore } from '@/stores/modules/user'
import { getCaptcha } from '@/api/auth'
import type { LoginForm } from '@/types/user'

// 路由
const router = useRouter()
const route = useRoute()

// 用户store
const userStore = useUserStore()

// 表单引用
const loginFormRef = ref<FormInstance>()

// 加载状态
const loading = ref(false)

// 验证码配置
const captchaEnabled = ref(false)
const captchaImg = ref('')

// 记住用户名
const rememberMe = ref(false)

// 登录表单数据
const loginForm = reactive<LoginForm>({
  username: '',
  password: '',
  code: '',
  uuid: '',
})

// 表单验证规则
const loginRules: FormRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 2, max: 30, message: '用户名长度在 2 到 30 个字符', trigger: 'blur' },
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 5, max: 20, message: '密码长度在 5 到 20 个字符', trigger: 'blur' },
  ],
  code: [
    { required: true, message: '请输入验证码', trigger: 'blur' },
    { min: 4, max: 5, message: '验证码长度在 4 到 5 个字符', trigger: 'blur' },
  ],
}

// 获取验证码
const getCaptchaCode = async () => {
  try {
    const { data } = await getCaptcha()
    captchaImg.value = data.img
    loginForm.uuid = data.uuid
    captchaEnabled.value = data.captchaEnabled || false
  } catch (error) {
    console.error('获取验证码失败:', error)
  }
}

// 处理登录
const handleLogin = async () => {
  if (!loginFormRef.value) return

  try {
    // 表单验证
    await loginFormRef.value.validate()
    
    loading.value = true
    
    // 执行登录
    await userStore.loginAction(loginForm)
    
    // 记住用户名
    if (rememberMe.value) {
      localStorage.setItem('kexilo-username', loginForm.username)
    } else {
      localStorage.removeItem('kexilo-username')
    }
    
    ElMessage.success('登录成功')
    
    // 获取重定向地址
    const redirect = (route.query.redirect as string) || '/'
    
    // 跳转到目标页面
    await router.push(redirect)
    
  } catch (error: any) {
    console.error('登录失败:', error)
    
    // 登录失败后刷新验证码
    if (captchaEnabled.value) {
      getCaptchaCode()
    }
    
    // 清空密码和验证码
    loginForm.password = ''
    loginForm.code = ''
    
    // 聚焦到密码输入框
    nextTick(() => {
      const passwordInput = document.querySelector('input[type="password"]') as HTMLInputElement
      passwordInput?.focus()
    })
  } finally {
    loading.value = false
  }
}

// 初始化
onMounted(async () => {
  // 获取验证码
  await getCaptchaCode()
  
  // 恢复记住的用户名
  const savedUsername = localStorage.getItem('kexilo-username')
  if (savedUsername) {
    loginForm.username = savedUsername
    rememberMe.value = true
  }
  
  // 聚焦到第一个输入框
  nextTick(() => {
    if (loginForm.username) {
      const passwordInput = document.querySelector('input[type="password"]') as HTMLInputElement
      passwordInput?.focus()
    } else {
      const usernameInput = document.querySelector('input[type="text"]') as HTMLInputElement
      usernameInput?.focus()
    }
  })
})

// 刷新验证码
const refreshCaptcha = () => {
  getCaptchaCode()
}

// 暴露刷新验证码方法
defineExpose({
  refreshCaptcha,
})
</script>

<style lang="scss" scoped>
.login {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  overflow: hidden;
  display: flex;
  align-items: center;
  justify-content: center;
}

.login-bg {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  overflow: hidden;
  z-index: 1;
}

.login-bg-item {
  position: absolute;
  width: 200px;
  height: 200px;
  background: rgba(255, 255, 255, 0.1);
  border-radius: 50%;
  animation: float 6s ease-in-out infinite;
  
  &:nth-child(1) {
    top: 10%;
    left: 10%;
    animation-delay: 0s;
  }
  
  &:nth-child(2) {
    top: 20%;
    right: 10%;
    width: 150px;
    height: 150px;
    animation-delay: 2s;
  }
  
  &:nth-child(3) {
    bottom: 10%;
    left: 20%;
    width: 100px;
    height: 100px;
    animation-delay: 4s;
  }
}

@keyframes float {
  0%, 100% {
    transform: translateY(0px) rotate(0deg);
  }
  50% {
    transform: translateY(-20px) rotate(180deg);
  }
}

.login-form {
  position: relative;
  z-index: 2;
  width: 100%;
  max-width: 400px;
  margin: 0 20px;
}

.login-form-wrapper {
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  border-radius: 16px;
  box-shadow: 0 25px 45px rgba(0, 0, 0, 0.1);
  padding: 40px;
  border: 1px solid rgba(255, 255, 255, 0.2);
}

.login-header {
  text-align: center;
  margin-bottom: 32px;
}

.login-logo {
  width: 64px;
  height: 64px;
  margin-bottom: 16px;
}

.login-title {
  font-size: 24px;
  font-weight: 600;
  color: #2c3e50;
  margin: 0 0 8px 0;
}

.login-subtitle {
  font-size: 14px;
  color: #7c8db5;
  margin: 0;
}

.login-form-content {
  .el-form-item {
    margin-bottom: 20px;
    
    &:last-child {
      margin-bottom: 0;
    }
  }
  
  .el-input {
    --el-input-border-radius: 8px;
    
    :deep(.el-input__wrapper) {
      box-shadow: 0 0 0 1px rgba(0, 0, 0, 0.1) inset;
      transition: all 0.2s ease;
      
      &:hover {
        box-shadow: 0 0 0 1px var(--el-color-primary) inset;
      }
      
      &.is-focus {
        box-shadow: 0 0 0 2px var(--el-color-primary) inset;
      }
    }
  }
}

.captcha-container {
  display: flex;
  gap: 12px;
}

.captcha-input {
  flex: 1;
}

.captcha-img {
  width: 120px;
  height: 40px;
  border-radius: 6px;
  overflow: hidden;
  cursor: pointer;
  border: 1px solid var(--el-border-color);
  transition: all 0.2s ease;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #f5f7fa;
  
  &:hover {
    border-color: var(--el-color-primary);
    transform: scale(1.02);
  }
  
  img {
    width: 100%;
    height: 100%;
    object-fit: cover;
  }
  
  .captcha-loading {
    font-size: 12px;
    color: #909399;
  }
}

.login-options {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
}

.forgot-password {
  font-size: 14px;
}

.login-footer {
  margin-top: 32px;
  text-align: center;
}

.copyright {
  font-size: 12px;
  color: #909399;
  margin: 0 0 12px 0;
}

.links {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 0;
  
  .el-link {
    font-size: 12px;
    padding: 0 8px;
  }
  
  .el-divider {
    margin: 0;
  }
}

// 响应式设计
@media (max-width: 768px) {
  .login-form {
    max-width: 320px;
    margin: 0 16px;
  }
  
  .login-form-wrapper {
    padding: 24px;
  }
  
  .login-title {
    font-size: 20px;
  }
  
  .captcha-container {
    flex-direction: column;
    gap: 8px;
  }
  
  .captcha-img {
    width: 100%;
    height: 50px;
  }
}

// 暗色主题适配
.dark {
  .login-form-wrapper {
    background: rgba(20, 20, 20, 0.95);
    border: 1px solid rgba(255, 255, 255, 0.1);
  }
  
  .login-title {
    color: #e5eaf3;
  }
  
  .login-subtitle {
    color: #a3a6ad;
  }
}
</style>
